import Vue from 'vue'
import Vuex from 'vuex'
import {
  merge
} from 'lodash'
import {
  Service
} from '../service'
import {
  Logger
} from '../helper'
Vue.use(Vuex)
const store = new Vuex.Store({
  state: {
    isLogin: false,
    userInfo: {},
    /* 
      初始值应该要去服务器获取
    */
    carts: [],
  },

  getters: {
    cartsQuantity(state) {
      return state.carts.length;
    }
  },

  mutations: {
    setIsLogin(state, v) {
      state.isLogin = v;
    },
    setUserInfo(state, v) {
      state.userInfo = v;
    },
    setCarts(state, v) {
      state.carts = v;
    }
  },
  actions: {
    login({
      commit
    }, data) {
      return new Promise((resolve, reject) => {
        Service.login(data)
          .then(res => {
            Logger.success(`login`, '登录成功')
            commit('setIsLogin', true);
            commit('setUserInfo', {
              avatar: require('../assets/img/user-center/avatar.png'),
              level: 12,
              nickName: '不是好人',
              gender: '男',
              integeral: 719
            });
            resolve()
          })
          .catch(e => {
            reject(e)
            Logger.error(`login`, '登录失败')
          })
      })
    },

    addProductToCarts({
      commit,
      state
    }, payload) {
      const id = payload.id;
      if (!id) {
        Logger.error('添加购物车必须要有id');
        return;
      }
      const hasId = state.carts.find(item => item.id === id);
      if (hasId) {
        return;
      }

      const carts = [...state.carts, payload];
      Logger.info('carts', JSON.stringify(carts, null, 2))
      commit('setCarts', carts);
      return true
    }
  }
})
export default store;